//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "ia\fn_landHelicopter.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private["_heli","_timeout","_landing","_landing_pos"];				
DEFAULT_PARAM(_heli,0,objNull);
DEFAULT_PARAM(_landing_pos,1,[]);

if (AND_ALSO(IS_OBJECT(_heli),(!isnull(_heli)))) then {
	_landing = OGETVAR(_heli,QGVAR(landing),false);
	if (!_landing && alive _heli  && canmove _heli) then {
		OSETVAR(_heli,QGVAR(landing),true);	
		_timeout = 0;
		
		// If no exact position is given, we use the default AI landing mechanism
		if (count _landing_pos <= 0) then {
			//Orders to land heli	
			_heli land "LAND";
			//Waits for land position	
			waituntil {!alive _heli || toUpper(landResult _heli) != "NOTREADY" };
			if (alive _heli && (toUpper(landResult _heli) == "NOTFOUND")) then { 
				TRACE("No valid landing zone");
				OSETVAR(_heli,QGVAR(landing),false);		
			} else {
				//1rt try-Waits until velocity and heigh are good for getting out
				_timeout = 60 + time;
				waituntil {!alive _heli || time > _timeout || ((abs(velocity _heli select 2)) <= 1 && ((position _heli) select 2) <= 0.7)};
					
				//2nd try-Waits until velocity and heigh are good for getting out
				if (((position _heli) select 2) > 2 && ((position _heli) select 2) < 30 && !surfaceiswater position _heli) then { 		
					_heli land "LAND";
					_timeout = 30 + time;
					waituntil {!alive _heli || time > _timeout || ((position _heli) select 2) > 30 || ( (abs(velocity _heli select 2)) <= 1 && ((position _heli) select 2) <= 0.7)};	
				};
			};
		} else {
			// TODO add MANDO HELI ROUTE LANDING HERE
		};
	} else {
		TRACE_1("Invalid Helicopter",ARR_3(!_landing && alive _heli  && canmove _heli));
	};
} else {
	TRACE("Invalid Parameter");
};
TRACE("End");
TMFPROFILERSTOP;